fse = require 'fs-extra'
traverse = require 'fs-tree-traverse'
fsp = require './fs-promises'

# FIXME 这个封装不必要，本来fs-promises是把node的fs接口promise化，这个又尝试转回来？- by alva

file_utils =

  #创建文件夹
  createDir : (path) ->
    fse.ensureDir path, (err) ->
      console.error(err) if err

  #创建文件
  createFile : (path) ->
    fse.ensureFile path, (err) ->
      console.error(err) if err

  # 创建文件(若存在则不管),并写入内容
  checkAndWrite : (path, content, callback) ->
    fse.ensureFile path, (err) ->
      callback.err(err) if err && callback.err
      fse.outputFile(path, content, (err) ->
        callback.err(err) if err && callback.err
        callback.success(content)
      )

  #读取文件内容
  readFile : (path, callback) ->
    fse.readFile(path, 'utf8', (err, data) ->
      callback.err(err) if err && callback.err
      callback.success(data)
    )

  #读取文件夹文件列表,返回一个文件名数组
  readDir : (path, callback) ->
    fse.ensureDir path, (err) ->
      callback.err(err) if err && callback.err
      traverse.list path ,(err, files) ->
        callback.err(err) if err && callback.err

        filenames = []
        for fullname in files
          path = fullname.split("/")
          filename = path[path.length-1]
          filenames.push({filename:filename})
        callback.success(filenames)

  #删除文件
  removeFile : (path) ->
    fse.remove path, (err) ->
      return console.log(err) if err



module.exports = file_utils
